import { useUserStore } from '@/stores'

// 基础地址
export const BASE_URL = 'http://47.108.58.48'

// 请求拦截器
const interceptor = {
  invoke: (options) => {
    // 开启加载
    uni.showLoading({
      title: '请求中...'
    })
    if (!options.url.startsWith('http')) {
      options.url = BASE_URL + options.url
    }
    options.header = {
      ...options.header,
      'Content-Type': 'application/json'
    }
    const userStore = useUserStore()
    const { token } = userStore
    if (token) {
      options.header.Authorization = token
    }
  }
}

uni.addInterceptor('request', interceptor)
uni.addInterceptor('uploadFile', interceptor)

// 自定义请求方法 - 添加响应拦截器
export function request({ url, method = 'GET', data = {} }) {
  return new Promise((resolve, reject) => {
    uni.request({
      url,
      method,
      data,
      success: (res) => {
        // 判断业务响应成功还是失败
        // 数据解构
        const { code, data, msg } = res.data

        // 失败了
        if (code !== 200000) {
          // 统一错误提示
          uni.showToast({
            title: msg || '网络繁忙,请稍后重试',
            icon: 'fail'
          })
          reject(new Error(msg))
          return
        }

        // 成功了, 剥离 data 数据
        resolve(data)
      },
      fail: (err) => {
        // 统一错误提示
        uni.showToast({
          title: err.errMsg
        })
        reject(err)
      },
      complete: () => {
        // 关闭加载
        uni.hideLoading()
      }
    })
  })
}

// 上传文件
export const uploadFile = ({ url, key, filePath }) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url,
      name: key,
      filePath,
      success: (res) => {
        try {
          const { data } = JSON.parse(res.data)
          resolve(data)
        } catch (e) {
          resolve(res.data)
        }
      },
      fail: (error) => {
        reject(error)
      },
      complete: () => {
        // 关闭加载
        uni.hideLoading()
      }
    })
  })
}
